<template>
  <BoTable
    :columns="columns"
    :request="getDeviceList"
    ref="tableRef"
    :row-selection="rowSelection"
    :show-index="true"
    row-key="id"
  >
  </BoTable>
  <FormModal :columns="item">
    <template #calibrationRecord>
      <FormItemRest>
        <BoTable
          hideSearch
          :columns="columnsRecord"
          height="auto"
          :request="_getCalibrationRecordList"
          ref="tableRecordRef"
          :row-selection="rowSelection"
          row-key="id"
        ></BoTable>
      </FormItemRest>
    </template>
  </FormModal>
  <!-- 设备标定预览 -->
  <Modal
    v-model:open="visible"
    :footer="false"
    :destroyOnClose="true"
    wrapClassName="view_modal"
  >
    <TriggerData
      :options="options"
      title="设备标定数据"
      show-witch="history"
      :deviceInfo="[deviceCode]"
    >
      <template #header></template>
      <template #innerHeader>
        <div class="elDeep">
          <span>设备标识</span>
          <span>{{ stationId }}</span>
        </div>
      </template>
    </TriggerData>
  </Modal>

  <!--设备标定  -->
  <SseModal />
</template>
<route lang="json">
{
  "name": "calibration",
  "meta": {
    "title": "设备标定"
  }
}
</route>
<script setup lang="tsx">
import { computed, provide, ref } from 'vue';
import {
  getDeviceManufacturerSelect,
  getDeviceModelSelect,
  getDevicePowerSelect,
  getDeviceProjectSelect,
} from '@/api';
import { deviceEnum } from '@/constants';
import { useFormModal } from '@boeyo/hooks';
import { useDicts } from '@boeyo/portal';
import { listToEnum, listToOption } from '@boeyo/shared';
import { BoFormProps, BoTable, BoTableProps } from '@boeyo/ui';
import { FormItemRest, Modal } from 'ant-design-vue';
import dayjs from 'dayjs';
import TriggerData from '@/components/triggerData/index.vue';
import { useSseModal } from '@/hooks/useSseModal';
import {
  downloadHistoryData,
  getCalibrationRecordList,
  getDeviceList,
} from './api';

const tableRef = ref();
const tableRecordRef = ref();
const selectKeys = ref<any[]>([]);
const rowSelection = computed<BoTableProps['rowSelection']>(() => {
  return {
    selectedRowKeys: selectKeys.value,
    onChange(values, all) {
      selectKeys.value = values;
    },
  };
});

// 获取表单下拉框数据
const mnufacturerOptions = ref<any[]>([]);
const manufacturerEnum = ref<Record<string, any>>({});

const powerOptions = ref<any[]>([]);
const powerEnum = ref<Record<string, any>>({});
const modelOptions = ref<any[]>([]);
const modelEnum = ref<Record<string, any>>({});
const init = () => {
  getDeviceManufacturerSelect(deviceEnum.SEISMOGRAPH).then(({ data }) => {
    mnufacturerOptions.value = listToOption(data, 'name', 'facId');
    manufacturerEnum.value = listToEnum(data, 'name', 'facId');
  });

  getDevicePowerSelect().then(({ data }) => {
    powerOptions.value = listToOption(data, 'powerSupplyName', 'id');
    powerEnum.value = listToEnum(data, 'powerSupplyName', 'id');
  });
  getDeviceModelSelect({ type: deviceEnum.SEISMOGRAPH }).then(({ data }) => {
    modelOptions.value = listToOption(data, 'model', 'modelId');
    modelEnum.value = listToEnum(data, 'model', 'modelId');
  });
};
init();

const dictArr = ['device_type', 'online_status', 'push_status'];
const { deviceTypeEnum, onlineStatusEnum, pushStatusEnum } = useDicts(dictArr);

const columns = computed<BoTableProps['columns']>(() => [
  {
    title: '硬件序列号',
    dataIndex: 'deviceCode',
  },
  {
    title: '设备编号',
    dataIndex: 'stationId',
  },
  {
    title: '设备类型',
    dataIndex: 'deviceType',
    valueEnum: deviceTypeEnum.value,
    hideInSearch: true,
  },
  {
    title: '设备型号',
    dataIndex: 'modelId',
    valueEnum: modelEnum.value,
    valueType: 'select',
  },
  {
    title: '设备厂商',
    dataIndex: 'facId',
    valueType: 'select',
    valueEnum: manufacturerEnum.value,
    ellipsis: true,
  },
  // {
  //   title: '所属项目',
  //   dataIndex: 'projectId',
  //   valueEnum: projectEnum.value,
  //   hideInSearch: true,
  // },
  {
    title: '设备状态',
    dataIndex: 'dataOnlineStatus',
    valueType: 'status',
    valueEnum: onlineStatusEnum.value,
    hideInSearch: true,
  },
  {
    title: '操作',
    dataIndex: 'operation',
    hideInSearch: true,
    fixed: 'right',
    actions: ({ record }) => [
      {
        text: '下发标定',
        hidden: record.status == '1',
        onClick(record) {
          onCalibration(record);
        },
      },
      {
        text: '标定记录',
        onClick(record) {
          onCalibrationRecord(record);
        },
      },
    ],
  },
]);

const columnsRecord = computed<BoTableProps['columns']>(() => [
  {
    title: '创建时间',
    dataIndex: 'createTime',
  },
  {
    title: '状态',
    dataIndex: 'status',
    valueType: 'status',
    valueEnum: pushStatusEnum.value,
  },
  {
    title: '文件时间',
    dataIndex: 'fileSize',
    customRender({ record }) {
      return (
        <div>
          {record.startTime}~{record.endTime}
        </div>
      );
    },
    width: 400,
  },
  {
    title: '日志',
    dataIndex: 'errorLog',
  },
  {
    title: '操作',
    dataIndex: 'operation',
    actions: ({ record }) => [
      {
        text: '预览',
        disabled: record.status == '1',
        onClick(record) {
          onPreview(record);
        },
      },
      {
        text: '下载',
        disabled: record.status == '1',
        onClick(record) {
          onDownload(record);
        },
      },
    ],
  },
]);

const item = computed<BoFormProps['columns']>(() => [
  {
    title: '',
    dataIndex: 'calibrationRecord',
    colProps: {
      span: 24,
    },
    formItemProps: {
      labelCol: { span: 0 },
      wrapperCol: { span: 24 },
    },
    valueType: 'input',
  },
]);

const { FormModal, open } = useFormModal({
  size: 'middle',
  column: 1,
});

// 下发标定
const { SseModal, open: openSse } = useSseModal();
const onCalibration = (record: any) => {
  Modal.confirm({
    title: '下发标定',
    content: `是否确认针对该设备下发标定？`,
    onOk: async () => {
      openSse({
        title: '下发标定',
        url: '/api/demarcate/startDemarcate',
        data: [record.stationId],
        onClose() {
          tableRef.value.refresh();
        },
      });
    },
  });
};

const calibrationDeviceId = ref(0);
const onCalibrationRecord = (record: any) => {
  calibrationDeviceId.value = record.deviceId;
  open({
    title: '标定记录',
    request: async (params: any) => {},
    defaultValue: { record },
  });
};

const _getCalibrationRecordList = (params: any) => {
  params.deviceId = calibrationDeviceId.value;
  return getCalibrationRecordList(params);
};

// 预览标记
// 标定记录时间
const timeFormat = 'YYYY-MM-DD HH:mm:ss';
const calibrationTime = ref({
  startTime: '',
  endTime: '',
  hideDatePicker: true,
});
const stationId = ref('');
const deviceCode = computed(() => stationId.value.replace(/\./, ''));
const visible = ref(false);
const options = computed(() => {
  return {
    leftTool: ['type', 'channel', 'deviceInfo'],
    dataTypeList: [
      {
        label: '加速度',
        value: 'accelerationData',
        disabled: false,
      },
    ],
    channelList: [
      {
        value: 'EIZ',
        label: 'EIZ-竖桥向',
        color: '#F16995',
      },
      {
        value: 'EIN',
        label: 'EIN-横桥向',
        color: '#77E3F9',
      },
      {
        value: 'EIE',
        label: 'EIE-纵桥向',
        color: '#DFC428',
      },
    ],
    deviceInfoList: [
      {
        label: deviceCode.value,
        value: deviceCode.value,
        disabled: false,
      },
    ],
  };
});
// 注入标定记录预览时间
provide('historyDataOption', calibrationTime);
const formatTime = (time, type: string) => {
  return type === 'subtract'
    ? dayjs(time).subtract(30, 'second').format(timeFormat) || ''
    : dayjs(time).add(30, 'second').format(timeFormat) || '';
};
const onPreview = async (record: any) => {
  calibrationTime.value.startTime = formatTime(record.startTime, 'subtract');
  calibrationTime.value.endTime = formatTime(record.endTime, 'add');

  visible.value = true;
  stationId.value = record.stationId.replace(/\./, '');
};

const onDownload = async (record: any) => {
  const params = {
    startTime: formatTime(record.startTime, 'subtract'),
    endTime: formatTime(record.endTime, 'add'),
    stationId: record.stationId.replace(/\./, ''),
  };
  await downloadHistoryData(params);
};
</script>

<style lang="scss" scoped>
/* 头部按钮 */
.elDeep {
  height: 30px;
  line-height: 30px;
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  color: #b1e2ff;
  width: 100%;
  & > span {
    &:first-child {
      margin-right: 10px;
      color: #ffffff;
      font-weight: bold;
    }
  }
}
</style>
